package com.evolution.model;

import com.evolution.listeners.OrganismListener;
import com.evolution.utils.RandomGenerator;

public class World {

	public final int WORLD_WIDTH = 30;
	public final int WORLD_HEIGHT = 30;
	
	public Space[][] spaces;
	
	public World(){
		spaces = new Space[WORLD_WIDTH][WORLD_HEIGHT];
		
		for(int x = 0;x < WORLD_WIDTH;x++){
			for(int y = 0;y < WORLD_HEIGHT;y++){
				spaces[x][y] = new Space(x,y);
				if(RandomGenerator.randomBoolean(40)){
					spaces[x][y].growFood();
				}
			}
		}
		
		OrganismRegistry.getInstance().addListener(new OrganismListener() {
			
			@Override
			public void organismRegistered(Organism organism, Organism parent) {
				organism.setSpace(getRandomAdjacentSpace(parent.getSpace()));
			}
			
			@Override
			public void organismDeregistered(Organism organism) {
				organism.setSpace(null);
			}
		});
	}
	
	private Space getRandomAdjacentSpace(Space space){
		boolean up = RandomGenerator.randomBoolean();
		boolean right = RandomGenerator.randomBoolean();
		
		int newX = space.x;
		int newY = space.y;
		
		if(right)
			newX++;
		else
			newX--;
		
		if(up)
			newY++;
		else
			newY--;
		
		if(newX >= WORLD_WIDTH)
			newX = 0;
		if(newX < 0)
			newX = WORLD_WIDTH - 1;
		
		if(newY >= WORLD_HEIGHT)
			newY = 0;
		if(newY < 0)
			newY = WORLD_HEIGHT - 1;
		
		return spaces[newX][newY];
	}
}
